# -*- coding: utf-8 -*-
"""
@Time ： 2024/4/10 18:32
@Auth ： 李天天
"""
import re
from logzero import logger

from Common.handle_pid import DHDevices
from solox.public.adb import adb

from solox.public.apm import AppPerformanceMonitor

dhd = DHDevices()


class MyAppPerformanceMonitor(AppPerformanceMonitor):
    def collectSysMemory(self):
        try:
            cmd = 'cat /proc/meminfo'
            output = adb.shell(cmd=cmd, deviceId=self.deviceId)
            mem_total = float(re.search(r'MemTotal:\s+(\d+)\s+kB', output).group(1))
            mem_free = float(re.search(r'MemAvailable:\s+(\d+)\s+kB', output).group(1))
            mem_rate = round((mem_total - mem_free) / 1024, 2)
        except Exception as e:
            mem_rate = 0
            logger.exception(e)
        return mem_rate


class HandleDevices:
    def __init__(self, pkgName):
        self.pkgName = pkgName

    def handle_main_device(self, deviceId_001):
        CPDemo_processListdic = dhd.getPidNew(deviceId=deviceId_001, pkgName=self.pkgName)
        apm_pid_main = None
        for each in CPDemo_processListdic:
            if each["pkgName"] == "com.arcvideo.car.video":
                pid_main = each["PID"]
                apm_pid_main = MyAppPerformanceMonitor(pkgName=self.pkgName, platform='Android',
                                                       deviceId=deviceId_001,
                                                       surfaceview=True,
                                                       noLog=False, pid=pid_main, record=False, collect_all=False)
            # elif each["pkgName"] == "com.arcvideo.sdk.demo:media_service":
            #     pid_server = each["PID"]
            #     apm_pid_server = MyAppPerformanceMonitor(pkgName=self.pkgName, platform='Android',
            #                                              deviceId=deviceId_001,
            #                                              surfaceview=True,
            #                                              noLog=False, pid=pid_server, record=False, collect_all=False)
        if apm_pid_main:
            return apm_pid_main



    def get_cpu(self, apm, cpu_num=None):
        if not cpu_num:
            cpu_num = 8
        result = apm.collectCpu()
        result["appCpuRate"] = result['appCpuRate'] * cpu_num
        result["systemCpuRate"] = result['systemCpuRate'] * cpu_num
        return result

    def get_mem(self, apm):
        return apm.collectMemory()['total']

    def get_sys_mem(self, apm):
        return apm.collectSysMemory()
